#!/usr/bin/perl

BEGIN {
	if(exists($ENV{CODEMGR_LIBS})) {
		push @INC,$ENV{CODEMGR_LIBS},"$ENV{CODEMGR_LIBS}/../bh";
	}
}

use cm2bug;
use Getopt::Long;
use File::Basename;
use Digest::SHA1;
use Data::Dumper;

$_PRG=basename($0);

sub usage {
	print STDERR "
Usage: $_PRG --table X [--dbfile D] field:value [...]

The following tables can have records inserted using this utility:
";
	print cm2bug->get_record_requirements;
	exit(1);
}

$ARG_comments=1;
$ARG_dbfile="dbfile";
if(!GetOptions(
	"comments!"	=> \$ARG_comments,
	"infile=s"	=> \$ARG_infile,
	"table=s"	=> \$ARG_table,
	"dbfile=s"	=> \$ARG_dbfile,
)) {
	usage;
}
if(! -f $ARG_dbfile) {
	print STDERR "Error: Specified database file does not exist!\n";
	exit 1;
}

if(!defined($ARG_table)) {
	usage;
}

#########################################################################
# Complain bitterly and die if a specified input file is not available.	#
#########################################################################

if(defined($ARG_infile) && $ARG_infile ne "-") {
	if(! -r $ARG_infile || ! -f $ARG_infile) {
		print STDERR "Error: Specified input file does not exist, or is not readable.\n";
		exit 1;
	}
}

if(defined($ARG_infile)) {

	#################################################################
	# Read in all field/value pairs from the file and stuff into	#
	# ARGV which is 'ignored' if --infile has been used.		#
	#################################################################

	if(!open($fd,$ARG_infile)) {
		print STDERR "Error: Unable to open '$ARG_infile':\n$!\n";
		exit 1;
	}

	@ARGV=();
	$cvar=undef; $cval="";
	while(<$fd>) {
		chomp;
		next if /^##COMMENT/ && $ARG_comments;
		if(/^[a-z0-9A-Z_\-]+:/) {
			my ($field,$val)=(/^([a-z0-9A-Z_\-]+):(.*)/);

			if(defined($cvar)) {
				$cval =~ s/[\n\s]+$//;
				if(length($cval)) {
					push @ARGV,"$cvar:$cval";
				}
			}
			$cvar=$field;
			$cval=$val;
		} else {
			if(defined($cvar)) {
				$cval.="\n$_";
			}
		}
	}
	close($fd);
	if(defined($cvar)) {
		$cval =~ s/[\n\s]+$//;
		if(length($cval)) {
			push @ARGV,"$cvar:$cval";
		}
	}
}

my $DBH = cm2bug->new($ARG_dbfile);
if(!defined($DBH)) {
	print STDERR "Error: Unable to open database $ARG_dbfile!\n";
	exit 1;
}

$r=$DBH->add_verified_record($ARG_table,@ARGV);
$DBH->disconnect;
if(!$r) {
	($cc,$rc)=$DBH->error;
	print "Error occured whilst adding record:\n";
	print STDERR "Error: $rc [rc=$cc]\n";
	exit(1);
}

exit(0);
